import { getPersonalChannelPage } from '../../api/personalChannel/index'
import config from '../../config/index'

Page({
  data: {
    currentPage: 1,
    searchKey: '',
    personalChannelList: [] as ListPersonalChannel[] | ListPersonalChannel[][]
  },
  onShow() {
    this.setData({
      currentPage: 1,
      searchKey: ''
    })
    this.initList(this.data.currentPage, this.data.searchKey)
  },
  onPullDownRefresh(){
    wx.showNavigationBarLoading();
    this.initList(1, '').then(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    })
  },
  onReachBottom() {
    wx.showLoading({title: '加载中'})
    let that = this
    that.setData({
      currentPage: this.data.currentPage + 1
    })
    getPersonalChannelPage(this.data.currentPage, this.data.searchKey)
    .then((res) => {
      if(res.statusCode === config.SUCCESS_CODE) {
        let channelRes = res.data.data
        let newList = [...this.data.personalChannelList, ...channelRes] as ListPersonalChannel[]
        that.setData({
          personalChannelList: newList
        })
        wx.hideLoading()
      }
    })
  },
  async initList(page: number, brand: string) {
    const res = await getPersonalChannelPage(page, brand)
    if(res.statusCode === config.SUCCESS_CODE) {
      let channelRes = res.data
      this.setData({
        personalChannelList: channelRes.data
      })
    } else {
      wx.showToast({
        title: '获取失败请重试',
        icon: 'error'
      })
    }
  },
  search() {
    this.initList(1, this.data.searchKey)
  },
  toDetail(e: any) {
    let id: string = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/personalChannelDetail/personalChannelDetail?id=${id}`
    })
  }
})